import React, { useEffect, useMemo, useState } from 'react';
import styles from './index.less';
import type { IRoute } from 'umi';
import { Layout, Menu } from 'antd';

import iconMap from './siderItem/siderItem';
import { menuRouter } from '@/config/routes';
import { history, useLocation } from 'umi';

interface SiderProps {
  collapsed: boolean;
}

const { Sider } = Layout;

const SiderC: React.FC<SiderProps> = (props) => {
  const { collapsed } = props;

  const { pathname } = useLocation();
  const [openKeys, setOpenKeys] = useState<string[]>([pathname]);
  const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
  const changePage = ({ key }: { key: string }) => {
    history.push(key);
  };

  // 设置当前展开的 subMenu
  const calcOpenKeys = (path: string) => {
    const paths = path.split('/').filter((item) => item);

    let str = '';
    let strArr: string[] = [];
    for (let i = 0; i < paths.length; i++) {
      str += `/${paths[i]}`;
      strArr.push(str);
    }
    return strArr;
  };

  useEffect(() => {
    setOpenKeys(calcOpenKeys(pathname));
    setSelectedKeys([pathname]);
  }, [pathname]);

  const onOpenChange = (allopenKey: string[]) => {
    if (allopenKey.length === 0 || allopenKey.length === 1) {
      return setOpenKeys(allopenKey);
    }
    const latestOpenKey = allopenKey[allopenKey.length - 1];
    if (latestOpenKey.includes(allopenKey[0])) {
      return setOpenKeys(allopenKey);
    }
    return setOpenKeys([latestOpenKey]);
  };

  const items = useMemo(() => {
    function loop(menuRouters: IRoute[]) {
      const menu: any[] = menuRouters.map((item) => {
        const children = item.routes ? { children: loop(item.routes) } : {};
        const key = item.path ? { key: item.path } : {};
        const label = item.title && !collapsed ? { label: item.title } : {};
        const icon = item.path ? { icon: iconMap[item.path] } : null;

        return { ...key, ...label, ...icon, ...children };
      });
      return menu;
    }
    return loop(menuRouter);
  }, [collapsed]);

  return (
    <Sider trigger={null} collapsible collapsed={collapsed}>
      <div className={styles.headerLogo}></div>
      <Menu
        theme="dark"
        mode="inline"
        onOpenChange={onOpenChange}
        openKeys={openKeys}
        selectedKeys={selectedKeys}
        items={items}
        onClick={changePage}
      />
    </Sider>
  );
};

export default SiderC;
